<?php if ( !defined('BASEPATH') ) exit('No direct script access allowed');
/** 
* Server Class 
* 
* @author Thy Ngoc
*/
class Server extends CI_Controller {

	// --------------------------------------------------------------------
	/** 
	* init function
	* 
	* @access private
	* @param null
	* @return null
	*/
	function __construct(){
        parent::__construct();

		$this->load->library('smarty3', '', 'smarty');
        
        require_once(APPPATH . 'modules/backend/autoload.php');        
        
        $this->load->library('login_manager');
        require_once(APPPATH . 'modules/backend/info.php');

        $this->login_manager->check_role('menu');
        $this->load->language('backend');
        
        $this->smarty->assign('language', $this->lang);
        $this->smarty->assign('message', $this->session->flashdata('message'));
        $this->smarty->assign('error_message', $this->session->flashdata('error_message'));
		//$this->output->enable_profiler(TRUE);
	}
	// --------------------------------------------------------------------
	/** 
	* init function, get para for jquery grid via ajax
	* 
	* @access public
	* @param null
	* @return array in json encode
	*/
	function jqgrid_jsoninit(){
		if(IS_AJAX){
			$server_obj = new Server_model();
			$metadata = $server_obj->jqgrid_metadata();
			echo json_encode($metadata);
		}
	}
	// --------------------------------------------------------------------
	/** 
	* data function, get data for jquery grid via ajax
	* 
	* @access public
	* @param null
	* @return array in json encode
	*/
	function jqgrid_jsondata(){
		if(IS_AJAX){
			// <field>..., level, left_id, isleaf (true, false), expand (true, false)
			$server_obj = new Server_model();
			$search = $this->input->post('_search');
			// Cau hinh tim kiem, sap xep tren obj quan he
			$relative_search = array();
			$relative_key = array_keys($relative_search);
			if($search == 'true'){
				$filters = json_decode($this->input->post('filters'));
				if(!empty($filters->groupOp) && !empty($filters->rules)){
					$server_obj->group_start();
					if($filters->groupOp == 'OR'){
						foreach($filters->rules as $rules){
							$searchField = $rules->field;
							$searchOper = $rules->op; // eq, ne, 'gt', 'ge', 'lt', 'le', bw, bn, ew, en, cn, nc, nu, nn, in, ni
							$searchString = $rules->data;
							if(in_array($searchField, $relative_key) && $searchString != ''){
								if($searchOper == 'eq'){
									$server_obj->or_where_related($searchField, $relative_search[$searchField], $searchString);
								}elseif($searchOper == 'ne'){
									$server_obj->or_where_related($searchField, $relative_search[$searchField].' !=', $searchString);
								}elseif($searchOper == 'gt'){
									$server_obj->or_where_related($searchField, $relative_search[$searchField].' >', $searchString);
								}elseif($searchOper == 'ge'){
									$server_obj->or_where_related($searchField, $relative_search[$searchField].' >=', $searchString);
								}elseif($searchOper == 'lt'){
									$server_obj->or_where_related($searchField, $relative_search[$searchField].' <', $searchString);
								}elseif($searchOper == 'le'){
									$server_obj->or_where_related($searchField, $relative_search[$searchField].' <=', $searchString);
								}elseif($searchOper == 'bw'){
									$server_obj->or_like_related($searchField, $relative_search[$searchField], $searchString, 'after');
								}elseif($searchOper == 'bn'){
									$server_obj->or_not_like_related($searchField, $relative_search[$searchField], $searchString, 'after');
								}elseif($searchOper == 'ew'){
									$server_obj->or_like_related($searchField, $relative_search[$searchField], $searchString, 'before');
								}elseif($searchOper == 'en'){
									$server_obj->or_not_like_related($searchField, $relative_search[$searchField], $searchString, 'before');
								}elseif($searchOper == 'cn'){
									$server_obj->or_like_related($searchField, $relative_search[$searchField], $searchString, 'both');
								}elseif($searchOper == 'nc'){
									$server_obj->or_not_like_related($searchField, $relative_search[$searchField], $searchString, 'both');
								}elseif($searchOper == 'nu'){
									$server_obj->or_where_related($searchField, $relative_search[$searchField].' IS NULL');
								}elseif($searchOper == 'nn'){
									$server_obj->or_where_related($searchField, $relative_search[$searchField].' IS NOT NULL');
								}elseif($searchOper == 'in'){
									$server_obj->or_where_in_related($searchField, $relative_search[$searchField], explode(';', $searchString));
								}elseif($searchOper == 'ni'){
									$server_obj->or_where_not_in_related($searchField, $relative_search[$searchField], explode(';', $searchString));
								}
							}elseif(in_array($searchField, $server_obj->fields) && $searchString != ''){
								if($searchOper == 'ne'){
									$server_obj->or_where($searchField, $searchString);
								}elseif($searchOper == 'ne'){
									$server_obj->or_where($searchField.' !=', $searchString);
								}elseif($searchOper == 'gt'){
									$server_obj->or_where($searchField.' >', $searchString);
								}elseif($searchOper == 'ge'){
									$server_obj->or_where($searchField.' >=', $searchString);
								}elseif($searchOper == 'lt'){
									$server_obj->or_where($searchField.' <', $searchString);
								}elseif($searchOper == 'le'){
									$server_obj->or_where($searchField.' <=', $searchString);
								}elseif($searchOper == 'bw'){
									$server_obj->or_like($searchField, $searchString, 'after');
								}elseif($searchOper == 'bn'){
									$server_obj->or_not_like($searchField, $searchString, 'after');
								}elseif($searchOper == 'ew'){
									$server_obj->or_like($searchField, $searchString, 'before');
								}elseif($searchOper == 'en'){
									$server_obj->or_not_like($searchField, $searchString, 'before');
								}elseif($searchOper == 'cn'){
									$server_obj->or_like($searchField, $searchString, 'both');
								}elseif($searchOper == 'nc'){
									$server_obj->or_not_like($searchField, $searchString, 'both');
								}elseif($searchOper == 'nu'){
									$server_obj->or_where($searchField.' IS NULL');
								}elseif($searchOper == 'nn'){
									$server_obj->or_where($searchField.' IS NOT NULL');
								}elseif($searchOper == 'in'){
									$server_obj->or_where_in($searchField, explode(';', $searchString));
								}elseif($searchOper == 'ni'){
									$server_obj->or_where_not_in($searchField, explode(';', $searchString));
								}
							}
						}
					}else{ // AND
						foreach($filters->rules as $rules){
							$searchField = $rules->field;
							$searchOper = $rules->op; // eq, ne, 'gt', 'ge', 'lt', 'le', bw, bn, ew, en, cn, nc, nu, nn, in, ni
							$searchString = $rules->data;
							if(in_array($searchField, $relative_key) && $searchString != ''){
								if($searchOper == 'eq'){
									$server_obj->where_related($searchField, $relative_search[$searchField], $searchString);
								}elseif($searchOper == 'ne'){
									$server_obj->where_related($searchField, $relative_search[$searchField].' !=', $searchString);
								}elseif($searchOper == 'gt'){
									$server_obj->where_related($searchField, $relative_search[$searchField].' >', $searchString);
								}elseif($searchOper == 'ge'){
									$server_obj->where_related($searchField, $relative_search[$searchField].' >=', $searchString);
								}elseif($searchOper == 'lt'){
									$server_obj->where_related($searchField, $relative_search[$searchField].' <', $searchString);
								}elseif($searchOper == 'le'){
									$server_obj->where_related($searchField, $relative_search[$searchField].' <=', $searchString);
								}elseif($searchOper == 'bw'){
									$server_obj->like_related($searchField, $relative_search[$searchField], $searchString, 'after');
								}elseif($searchOper == 'bn'){
									$server_obj->not_like_related($searchField, $relative_search[$searchField], $searchString, 'after');
								}elseif($searchOper == 'ew'){
									$server_obj->like_related($searchField, $relative_search[$searchField], $searchString, 'before');
								}elseif($searchOper == 'en'){
									$server_obj->not_like_related($searchField, $relative_search[$searchField], $searchString, 'before');
								}elseif($searchOper == 'cn'){
									$server_obj->like_related($searchField, $relative_search[$searchField], $searchString, 'both');
								}elseif($searchOper == 'nc'){
									$server_obj->not_like_related($searchField, $relative_search[$searchField], $searchString, 'both');
								}elseif($searchOper == 'nu'){
									$server_obj->where_related($searchField, $relative_search[$searchField].' IS NULL');
								}elseif($searchOper == 'nn'){
									$server_obj->where_related($searchField, $relative_search[$searchField].' IS NOT NULL');
								}elseif($searchOper == 'in'){
									$server_obj->where_in_related($searchField, $relative_search[$searchField], explode(';', $searchString));
								}elseif($searchOper == 'ni'){
									$server_obj->where_not_in_related($searchField, $relative_search[$searchField], explode(';', $searchString));
								}
							}elseif(in_array($searchField, $server_obj->fields) && $searchString != ''){
								if($searchOper == 'eq'){
									$server_obj->where($searchField, $searchString);
								}elseif($searchOper == 'ne'){
									$server_obj->where($searchField.' !=', $searchString);
								}elseif($searchOper == 'gt'){
									$server_obj->where($searchField.' >', $searchString);
								}elseif($searchOper == 'ge'){
									$server_obj->where($searchField.' >=', $searchString);
								}elseif($searchOper == 'lt'){
									$server_obj->where($searchField.' <', $searchString);
								}elseif($searchOper == 'le'){
									$server_obj->where($searchField.' <=', $searchString);
								}elseif($searchOper == 'bw'){
									$server_obj->like($searchField, $searchString, 'after');
								}elseif($searchOper == 'bn'){
									$server_obj->not_like($searchField, $searchString, 'after');
								}elseif($searchOper == 'ew'){
									$server_obj->like($searchField, $searchString, 'before');
								}elseif($searchOper == 'en'){
									$server_obj->not_like($searchField, $searchString, 'before');
								}elseif($searchOper == 'cn'){
									$server_obj->like($searchField, $searchString, 'both');
								}elseif($searchOper == 'nc'){
									$server_obj->not_like($searchField, $searchString, 'both');
								}elseif($searchOper == 'nu'){
									$server_obj->where($searchField.' IS NULL');
								}elseif($searchOper == 'nn'){
									$server_obj->where($searchField.' IS NOT NULL');
								}elseif($searchOper == 'in'){
									$server_obj->where_in($searchField, explode(';', $searchString));
								}elseif($searchOper == 'ni'){
									$server_obj->where_not_in($searchField, explode(';', $searchString));
								}
							}
						}
					}
					$server_obj->group_end();
				}else{
					$searchField = $this->input->post('searchField');
					$searchOper = $this->input->post('searchOper'); // eq, ne, 'gt', 'ge', 'lt', 'le', bw, bn, ew, en, cn, nc, nu, nn, in, ni
					$searchString = $this->input->post('searchString');
					if(in_array($searchField, $relative_key)){
						if($searchOper == 'eq'){
							$server_obj->where_related($searchField, $relative_search[$searchField], $searchString);
						}elseif($searchOper == 'ne'){
							$server_obj->where_related($searchField, $relative_search[$searchField].' !=', $searchString);
						}elseif($searchOper == 'gt'){
							$server_obj->where_related($searchField, $relative_search[$searchField].' >', $searchString);
						}elseif($searchOper == 'ge'){
							$server_obj->where_related($searchField, $relative_search[$searchField].' >=', $searchString);
						}elseif($searchOper == 'lt'){
							$server_obj->where_related($searchField, $relative_search[$searchField].' <', $searchString);
						}elseif($searchOper == 'le'){
							$server_obj->where_related($searchField, $relative_search[$searchField].' <=', $searchString);
						}elseif($searchOper == 'bw'){
							$server_obj->like_related($searchField, $relative_search[$searchField], $searchString, 'after');
						}elseif($searchOper == 'bn'){
							$server_obj->not_like_related($searchField, $relative_search[$searchField], $searchString, 'after');
						}elseif($searchOper == 'ew'){
							$server_obj->like_related($searchField, $relative_search[$searchField], $searchString, 'before');
						}elseif($searchOper == 'en'){
							$server_obj->not_like_related($searchField, $relative_search[$searchField], $searchString, 'before');
						}elseif($searchOper == 'cn'){
							$server_obj->like_related($searchField, $relative_search[$searchField], $searchString, 'both');
						}elseif($searchOper == 'nc'){
							$server_obj->not_like_related($searchField, $relative_search[$searchField], $searchString, 'both');
						}elseif($searchOper == 'nu'){
							$server_obj->where_related($searchField, $relative_search[$searchField].' IS NULL');
						}elseif($searchOper == 'nn'){
							$server_obj->where_related($searchField, $relative_search[$searchField].' IS NOT NULL');
						}elseif($searchOper == 'in'){
							$server_obj->where_in_related($searchField, $relative_search[$searchField], explode(';', $searchString));
						}elseif($searchOper == 'ni'){
							$server_obj->where_not_in_related($searchField, $relative_search[$searchField], explode(';', $searchString));
						}
					}elseif(in_array($searchField, $server_obj->fields)){
						if($searchOper == 'eq'){
							$server_obj->where($searchField, $searchString);
						}elseif($searchOper == 'ne'){
							$server_obj->where($searchField.' !=', $searchString);
						}elseif($searchOper == 'gt'){
							$server_obj->where($searchField.' >', $searchString);
						}elseif($searchOper == 'ge'){
							$server_obj->where($searchField.' >=', $searchString);
						}elseif($searchOper == 'lt'){
							$server_obj->where($searchField.' <', $searchString);
						}elseif($searchOper == 'le'){
							$server_obj->where($searchField.' <=', $searchString);
						}elseif($searchOper == 'bw'){
							$server_obj->like($searchField, $searchString, 'after');
						}elseif($searchOper == 'bn'){
							$server_obj->not_like($searchField, $searchString, 'after');
						}elseif($searchOper == 'ew'){
							$server_obj->like($searchField, $searchString, 'before');
						}elseif($searchOper == 'en'){
							$server_obj->not_like($searchField, $searchString, 'before');
						}elseif($searchOper == 'cn'){
							$server_obj->like($searchField, $searchString, 'both');
						}elseif($searchOper == 'nc'){
							$server_obj->not_like($searchField, $searchString, 'both');
						}elseif($searchOper == 'nu'){
							$server_obj->where($searchField.' IS NULL');
						}elseif($searchOper == 'nn'){
							$server_obj->where($searchField.' IS NOT NULL');
						}elseif($searchOper == 'in'){
							$server_obj->where_in($searchField, explode(';', $searchString));
						}elseif($searchOper == 'ni'){
							$server_obj->where_not_in($searchField, explode(';', $searchString));
						}
					}
				}
			}else{
				$id = intval($this->session->userdata('search_id'));
				if($id>0){
					$server_obj->where('id', $id);
					$this->session->unset_userdata('search_id');
				}
			}
			// Lay cac truong quan he neu co
			if(!empty($relative_search)){
				foreach($relative_search as $key => $value){
					$server_obj->include_related($key, 'title');
				}
			}
			// Order
			$order = $this->input->post('sidx');
			$order_direct = $this->input->post('sord');
			if(!empty($order) && in_array($order_direct, array('asc', 'desc'))){
				if(in_array($order, $relative_key)){
					$server_obj->order_by($order.'_'.$relative_search[$order], $order_direct);			
				}elseif(in_array($order, $server_obj->fields)){
					$server_obj->order_by($order, $order_direct);
				}
			}
			// Page
			$page = intval($this->input->post('page'));
			if($page <= 0) $page = 1;
			
			$num_per_page = intval($this->input->post('rows'));
			if($num_per_page <= 0) $num_per_page = $this->num_per_page;
			
			$server_obj->get_paged($page, $num_per_page);
			$paged = $server_obj->paged;
			
			$responce = new Stdclass();
			$responce->page = $paged->current_page; //curent page
			$responce->total = $paged->total_pages; //total page 
			$responce->records = $paged->total_rows; //total record
			$i = 0;
			foreach($server_obj as $obj){
				$isLeaf = TRUE;
				$responce->rows[$i]['cell'] = array(
					// Field
					$obj->id,
					$obj->server,
					$obj->name,
					$obj->partner,
					$obj->dns,
                    $obj->merge,
					// Format
					NULL,
					NULL,
					$isLeaf,
					false
				);
				$i++;
			}
			echo json_encode($responce);
		}
	}
	// --------------------------------------------------------------------
	/** 
	* index function, show jquery grid
	* 
	* @access public
	* @param null
	* @return void
	*/
	function index(){
		$array_para = $this->uri->ruri_to_assoc();
		if(isset($array_para['id'])){
			$id = intval($array_para['id']);
			if($id>0){
				$this->session->set_userdata('search_id', $id);
			}
		}
        
        $css_files = array(base_url() . 'data/jscripts/jqgrid/css/ui.jqgrid.css');

        $js_files = array(
            base_url() . 'data/jscripts/jqgrid/i18n/grid.locale-vi.js',
            base_url() . 'data/jscripts/jqgrid/jquery.jqGrid.min.js'
        );

        require_once(APPPATH . 'modules/backend/history.php');
        
		$server_obj = new Server_model();
		// Nap cac thong so de khoi tao jqgrid
		$jqgrid = array();
		$jqgrid['id'] = 'jqgrid';
		$jqgrid['pager'] = 'pagered'; // id pager
		$jqgrid['caption'] = $server_obj->localize_label('manager');
		$jqgrid['url_metadata'] = site_url($this->router->directory.'server/jqgrid_jsoninit');
		$jqgrid['url_data'] = site_url($this->router->directory.'server/jqgrid_jsondata');
		$jqgrid['url_create'] = site_url($this->router->directory.'server/create');
		$jqgrid['url_edit'] = site_url($this->router->directory.'server/edit');
		$jqgrid['url_delete'] = site_url($this->router->directory.'server/delete');
        
        $this->smarty->assign('jqgrid', $jqgrid);
        $jqgrid_init = $this->smarty->get_contents('template/backend/js/jqgrid');
		$js_text = array($jqgrid_init);
        
		// Nap cac file css va js
		$this->smarty->assign('css_files', $css_files);
		$this->smarty->assign('js_files', $js_files);
		$this->smarty->assign('js_text', $js_text);
		$this->smarty->assign('tieude', $server_obj->localize_label('manager'));
		// view
		$this->smarty->view('backend/server/jqgrid', 'grid');
        $this->smarty->display('template/backend/admin');
	}
	// --------------------------------------------------------------------
	/** 
	* create function, create new object
	* 
	* @access public
	* @param null
	* @return void
	*/
    public function create() {    	
        $this->edit();
    }

    public function edit() {
    	$id = $this->uri->rsegment(4)!=""?$this->uri->rsegment(4):$this->input->post('id');
		$server_obj = new Server_model($id);
		
		$this->smarty->assign('server_obj', $server_obj);
		
        if ($this->input->server('REQUEST_METHOD') === 'GET') {
            $this->smarty->view('backend/server/edit', 'main_content');
            $this->smarty->display('template/backend/admin');
        } else {
            $this->load->library('form_validation');
            
            $rules = array(
            		array(
            				'field' => 'server',
            				'label' => 'Server',
            				'rules' => 'required'
            		),
            		array(
            				'field' => 'name',
            				'label' => 'Name',
            				'rules' => 'required'
            		),
            		array(
            				'field' => 'dns',
            				'label' => 'DNS',
            				'rules' => 'required'
            		),
            		array(
            				'field' => 'partner',
            				'label' => 'Đối tác',
            				'rules' => 'required'
            		),
            		array(
            				'field' => 'merge',
            				'label' => 'Merge',
            				'rules' => 'required'
            		),
            );
            
            $this->form_validation->set_rules($rules);

            if ($this->form_validation->run() == TRUE) {
                $this->_save(site_url('auth/server'), $server_obj);
            } else {
            	//print_r($_SERVER);
            	//exit;
                $this->smarty->view('backend/server/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            }
        }
    }

   function _save($uri, $obj) {
    	//$obj = new Server_model();
    	//print_r($obj);
    	//exit;
        // Begin transaction
        $obj->trans_begin();

        $obj->server 	= $this->input->post('server'); 
        $obj->name 		= $this->input->post('name');
        $obj->dns 		= $this->input->post('dns');
        $obj->partner 	= $this->input->post('partner');
        $obj->merge 	= $this->input->post('merge');

        $obj->save();
        //$obj->check_last_query();
        //exit;
        $exists = $obj->exists();
        // Attempt to save user
        // Check status of transaction
        if ($obj->trans_status() === FALSE) {
            // Transaction failed, rollback
            $obj->trans_rollback();

            // Add error message
            $u->error_message('transaction', 'The transaction failed to save (insert)');
        } else {
            // Transaction successful, commit
            $obj->trans_commit();

            if ($exists) {
                $this->session->set_flashdata('message', $obj->localize_label('edit_success') /* 'Đã cập nhật dữ liệu thành công.' */);
            } else {
                $this->session->set_flashdata('message', $obj->localize_label('create_success')/* 'Đã lưu dữ liệu thành công.' */);
            }
            redirect($uri);
        }
        // Show all errors
        $error = $category->error->string;

        $this->session->set_flashdata('message', $error);
        edirect($uri);
    }

    /**
     * delete function, delete exists object
     *
     * @access public
     * @param id of object in url
     * @return void
     */
    function delete() {
        $url = 'server/index';

        $parameters = $this->uri->ruri_to_assoc();

        if (isset($parameters['id'])) {
            $id = intval($parameters['id']);
        } else {
            $id = 0;
        }

        if ($id <= 0) {
            //$this->session->set_flashdata('message', $this->lang->line('no_access_direct'));
            $this->session->set_flashdata('error_message', $this->lang->line('no_found'));
            redirect($this->router->directory . $url);
        }

        $obj = new Server_model();
        $obj->where('id', $id);
        $obj->get(1);

        if ($obj->id <= 0) {
            //$this->session->set_flashdata('message', $this->lang->line('invalide_id'));
            $this->session->set_flashdata('error_message', $this->lang->line('no_found'));
            redirect($this->router->directory . $url);
        }

        $result = $obj->delete();
        if ($result === TRUE) {
            $this->session->set_flashdata('message', $obj->localize_label('delete_success'));
        } else {
            
            if($result == -1){
				$this->session->set_flashdata('message', $obj->localize_label('delete_news_first'));
			}elseif($result == -2){
				$this->session->set_flashdata('message', $obj->localize_label('delete_subcategory_first'));
			}else{
				$this->session->set_flashdata('message', $obj->localize_label('delete_fail'));
			}
            
            
            
          
        }
        redirect($this->router->directory . $url);
    }
}
/* End of file server.php */
/* Location: ./system/application/controllers/backend/server.php */